package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.api.service.WeAppMessageService;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.exception.BusinessException;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.dto.DepartmentDto;
import com.yixun.qfbao.model.dto.Organization;
import com.yixun.qfbao.model.dto.WxmsgFailureDto;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.service.*;
import com.yixun.qfbao.util.TemplateMessageResult;
import com.yixun.qfbao.util.WxAccessTokenCacheUtils;
import com.yixun.qfbao.weappmessage.WeAppMessageProperties;
import com.yixun.qfbao.weappmessage.aes.SHA1;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WeAppMessageServiceImpl implements WeAppMessageService {

    private static final Logger logger = LoggerFactory.getLogger(WeAppMessageServiceImpl.class);

    @Autowired
    private WeAppMessageProperties weAppMessageProperties;
    @Autowired
    private WxAccessTokenCacheUtils wxAccessTokenCacheUtils;
    @Autowired
    private WeappFormidService weappFormidService;
    @Autowired
    private PartnerInfoService partnerInfoService;
    @Autowired
    private PremisesService premisesService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private WxmsgFailureService wxmsgFailureService;

    /**
     *
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param echostr 随机字符串
     * @return
     */
    public String check(String signature, String timestamp, String nonce, String echostr){
        try {
            logger.info("check params:", "signature ==> " + signature + ",timestamp ==>" + timestamp + ",nonce ==>" + nonce + ",echostr ==>" + echostr);
            //消息推送 token，小程序平台上配置的值，自己设置，可随意
            String token = weAppMessageProperties.getWeAppAgencyMessageToken();
            //本地的签名
            String localSignature = SHA1.getSHA1(token, timestamp, nonce, null);
            if (signature.equals(localSignature)) {
                return echostr;
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new BusinessException("9999", "sha加密生成签名失败");
        }
    }

    @Override
    public void sendWeAppAgencyMsg(Map<String, String> weappAgencyMsgMap, String sendType) {
//        TemplateMessageResult templateMessageResult = new TemplateMessageResult();
//        Long cusPreId = Long.valueOf(weappAgencyMsgMap.get("id"));
//        Long staffId = Long.valueOf(weappAgencyMsgMap.get("staffId"));
//        String companyUuid = weappAgencyMsgMap.get("companyUuid");
//        WeappFormidDto dto = new WeappFormidDto();
//        dto.setUserId(String.valueOf(staffId));
//        dto.setIsUsed(IsUsedEnum.UNUSED.getNo());
//        dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
//        WeappFormid weappFormid = weappFormidService.selectValidFormId(dto);
//
//        if(null == weappFormid){
//            templateMessageResult.setErrmsg("用户FormId缺失,无法发送消息!");
//            buildWXFailureMsg(companyUuid, SystemIdEnum.WEAPP_AGENCY.getCode(), "", "", "", "", templateMessageResult, cusPreId);
//            return;
//        }
//
//        PartnerInfo agencyPartner = partnerInfoService.selectById(staffId);
//        if(null == agencyPartner){
//            templateMessageResult.setErrmsg("用户不存在!");
//            buildWXFailureMsg(companyUuid, SystemIdEnum.WEAPP_AGENCY.getCode(), "", "", "", "", templateMessageResult, cusPreId);
//            return;
//        }
//
//        List<String> sendContentList = buildMsgForAgencyWeApp(weappAgencyMsgMap, sendType, agencyPartner);
//
//        Map<String, Object> map = new HashMap<>();
//        String weappModelType = "";
//        String weappModelId = "";
//        map.put(WeAppMessageConstant.TO_USER, agencyPartner.getWeappOpenid());
//        if(WeAppSendTypeEnum.AGENCY_AUDIT_SUCCESS.getNo().equals(sendType)){
//            map.put(WeAppMessageConstant.TEMPLATE_ID, WeAppMessageTemplate.TEMPLATE_REPORT_AUDIT_SUCCESS);
//            weappModelType = WeAppSendTypeEnum.AGENCY_AUDIT_SUCCESS.getNo();
//            weappModelId = WeAppMessageTemplate.TEMPLATE_REPORT_AUDIT_SUCCESS;
//        }else if(WeAppSendTypeEnum.AGENCY_AUDIT_FAILURE.getNo().equals(sendType)){
//            map.put(WeAppMessageConstant.TEMPLATE_ID, WeAppMessageTemplate.TEMPLATE_REPORT_AUDIT_FAILURE);
//            weappModelType = WeAppSendTypeEnum.AGENCY_AUDIT_FAILURE.getNo();
//            weappModelId = WeAppMessageTemplate.TEMPLATE_REPORT_AUDIT_FAILURE;
//        }else if(WeAppSendTypeEnum.AGENCY_TRADE_SUCCESS.getNo().equals(sendType)){
//            map.put(WeAppMessageConstant.TEMPLATE_ID, WeAppMessageTemplate.TEMPLATE_REPORT_TRADE_SUCCESS);
//            weappModelType = WeAppSendTypeEnum.AGENCY_TRADE_SUCCESS.getNo();
//            weappModelId = WeAppMessageTemplate.TEMPLATE_REPORT_TRADE_SUCCESS;
//        }else if(WeAppSendTypeEnum.AGENCY_TRADE_FAILURE.getNo().equals(sendType)){
//            map.put(WeAppMessageConstant.TEMPLATE_ID, WeAppMessageTemplate.TEMPLATE_REPORT_TRADE_FAILURE);
//            weappModelType = WeAppSendTypeEnum.AGENCY_TRADE_FAILURE.getNo();
//            weappModelId = WeAppMessageTemplate.TEMPLATE_REPORT_TRADE_FAILURE;
//        }
//        map.put(WeAppMessageConstant.PAGE, "");
//        map.put(WeAppMessageConstant.FORM_ID, weappFormid.getFormId());
//        map.put(WeAppMessageConstant.DATA, bulidTemplateData(sendContentList));
//
//        Map<String, Object> requestMap = new HashMap<>();
//        requestMap.put(WeAppMessageConstant.ACCESS_TOKEN, wxAccessTokenCacheUtils.getWeAppAgencyAccessToken());
//        //发送模版消息给接收人
//        logger.info("weapp msg send content", JSONObject.toJSONString(map));
//        String result =  RestTemplateUtil.post(RestTemplateUtil.buildGetUrl(WxConstant.SEND_WEAPPA_TEMPLATE_MESSAGE, requestMap), map);
//        templateMessageResult = JSON.parseObject(result, TemplateMessageResult.class);
//        logger.info("weapp msg send response", result);
//        JSONObject json = JSONObject.parseObject(result);
//        buildWXFailureMsg(companyUuid, SystemIdEnum.WEAPP_AGENCY.getCode(), agencyPartner.getWeappOpenid(), JSONObject.toJSONString(map), weappModelType, weappModelId, templateMessageResult, cusPreId);
//
//        dto = new WeappFormidDto();
//        if(null != weappFormid.getId()){
//            dto.setId(weappFormid.getId());
//            weappFormidService.destroy(dto);
//        }
    }

    private Map<String, Map<String, String>> bulidTemplateData(List<String> list) {
        Map<String, Map<String, String>> keyMap = new LinkedHashMap<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, String> valueMap = new HashMap<>();
            String keyIndex = String.valueOf(i + 1);
            valueMap.put("value", list.get(i));
            keyMap.put("keyword" + keyIndex, valueMap);
        }
        return keyMap;
    }

    /**
     * 创建分销小程序内容主体
     * @param weappAgencyMsgMap
     * @param sendType
     * @return
     */
    List<String> buildMsgForAgencyWeApp(Map<String, String> weappAgencyMsgMap, String sendType, PartnerInfo agencyPartner){
        List<String> result = new ArrayList<>();
        Long id = Long.valueOf(weappAgencyMsgMap.get("id"));
        Long premisesId = Long.valueOf(weappAgencyMsgMap.get("premisesId"));
        Long staffId = Long.valueOf(weappAgencyMsgMap.get("staffId"));
        String customerName = weappAgencyMsgMap.get("customerName");
        String customerPhone = weappAgencyMsgMap.get("customerPhone");
        String createTime = weappAgencyMsgMap.get("createTime");
        String hopeVisitTime = weappAgencyMsgMap.get("hopeVisitTime");
        String changeStatus = weappAgencyMsgMap.get("changeStatus");
        String changeTime = weappAgencyMsgMap.get("changeTime");
        String failureDesc = weappAgencyMsgMap.get("failureDesc");
        String remark = weappAgencyMsgMap.get("remark");
        // 楼盘名称
        Premises premises = premisesService.selectSimpleById(premisesId);
        String premisesName = premises != null && StringUtils.isNotBlank(premises.getName()) ? premises.getName() : "";
        // 对接人姓名
        DepartmentDto departDto = departmentDao.getPrincipal(staffId);
        String principalName ="";
        if(departDto!=null){
            principalName = StringUtils.isEmpty(departDto.getPrincipalName())?"":departDto.getPrincipalName();
        }
        String premisesContent = premisesName;
        if(StringUtils.isNotBlank(principalName)){
            premisesContent += " 对接人: " + principalName;
        }
        Organization organization = companyService.getOrganizationInfo(agencyPartner.getHigherid(), agencyPartner.getDeptId());
        String source = organization.getCompanyName() + " " + organization.getGroupName() + " " + agencyPartner.getAccountName() + " " + agencyPartner.getPhone();
        if(WeAppSendTypeEnum.AGENCY_AUDIT_SUCCESS.getNo().equals(sendType)){
            result.add(premisesContent);
            result.add(customerName);
            result.add(customerPhone);
            result.add(createTime);
            result.add(hopeVisitTime);
            result.add(source);
            result.add("报备确认成功，可带看客户");
        }else if(WeAppSendTypeEnum.AGENCY_AUDIT_FAILURE.getNo().equals(sendType)){
            result.add(failureDesc);
            result.add(premisesContent);
            result.add(customerName);
            result.add(customerPhone);
            result.add(createTime);
            result.add(hopeVisitTime);
            result.add(source);
        }else if(WeAppSendTypeEnum.AGENCY_TRADE_SUCCESS.getNo().equals(sendType)){
            result.add(premisesContent);
            result.add(customerName);
            result.add(customerPhone);
            result.add(changeStatus);
            result.add(organization.getCompanyName());
            result.add(changeTime);
            result.add("恭喜【"+ changeStatus +"】  成功！请及时更近后续业务");
        }else if(WeAppSendTypeEnum.AGENCY_TRADE_FAILURE.getNo().equals(sendType)){
            if(StringUtils.isNotBlank(remark)){
                result.add("有一条报备交易失败，失败原因：" + remark);
            }else{
                result.add("有一条报备交易失败");
            }
            result.add(premisesContent);
            result.add(customerName);
            result.add(customerPhone);
            result.add(failureDesc);
            result.add(changeTime);
            result.add(organization.getCompanyName());
        }
        return result;
    }

    private void buildWXFailureMsg(String companyUuid, String systemId, String openId, String content, String wxmodelType, String wxmodelUuid, TemplateMessageResult result, Long cusPreid){
        WxmsgFailureDto wfDto = new WxmsgFailureDto();
        if(StringUtils.isEmpty(companyUuid)){
            return;
        }
        wfDto.setCompanyUuid(companyUuid);
        wfDto.setSystemId(systemId);
        wfDto.setReceiveOpenid(openId);
        wfDto.setCusPreid(cusPreid);
        wfDto.setReceiveContent(content);
        wfDto.setWxmodelType(wxmodelType);
        wfDto.setWxmodelUuid(wxmodelUuid);
        wfDto.setIsResend(false);
        if(!"ok".equals(result.getErrmsg().toLowerCase())) {
            //根据之前的SQL 判定是否进行重发机制  result like '%40001%' OR result like '%system error%'
            if (40001 == result.getErrcode() || StringUtils.contains(result.getErrmsg(),"system error")){
                wfDto.setIsResend(true);
                wfDto.setSendStatus(SendStatusEnum.RESEND.getNo());
            }else {
                wfDto.setSendStatus(SendStatusEnum.FAILURE.getNo());
            }
        }else{
            wfDto.setSendStatus(SendStatusEnum.SUCCESS.getNo());
        }
        wfDto.setResult(JSONObject.toJSONString(result));
        wfDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        wfDto.setCreateTime(Calendar.getInstance().getTime());
        wxmsgFailureService.create(wfDto);
    }

}
